﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;

namespace PSE.Deployment.Util
{
    public class Certificate
    {
        public static bool CheckAccess(StoreName storeName)
        {
            bool accessAccepted = true;

            try
            {
                X509Store store = new X509Store(storeName, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Close();
            }
            catch
            {
                accessAccepted = false;
            }

            return accessAccepted;
        }

        public static void AddCertificate(StoreName storeName, StoreLocation storeLocation, string certificateFile, string password)
        {
            X509Store store = new X509Store(storeName, storeLocation);
            
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite | OpenFlags.MaxAllowed | OpenFlags.IncludeArchived);
            
            store.Add(new X509Certificate2(certificateFile, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable));
            
            store.Close();
        }

        public static void RemoveCertificate(StoreName storeName, StoreLocation storeLocation, string certificateFile, string password)
        {
            X509Store store = new X509Store(storeName, storeLocation);
            
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite | OpenFlags.MaxAllowed | OpenFlags.IncludeArchived);

            X509Certificate2 certificate = new X509Certificate2(certificateFile, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            store.Remove(certificate);

            store.Close();
        }
    }
}
